import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# 随机行走的步数
steps = 1000

# 初始位置
x = np.zeros(steps)
y = np.zeros(steps)

# 模拟随机行走
for i in range(1, steps):
    # 在[-1, 0, 1]中随机选择方向
    direction = np.random.randint(0, 4)
    if direction == 0:
        x[i] = x[i - 1] + 1  # 向右移动
        y[i] = y[i - 1]
    elif direction == 1:
        x[i] = x[i - 1] - 1  # 向左移动
        y[i] = y[i - 1]
    elif direction == 2:
        y[i] = y[i - 1] + 1  # 向上移动
        x[i] = x[i - 1]
    else:
        y[i] = y[i - 1] - 1  # 向下移动
        x[i] = x[i - 1]

# 创建图表和动画
fig, ax = plt.subplots()
ax.set_xlim([np.min(x)-10, np.max(x)+10])
ax.set_ylim([np.min(y)-10, np.max(y)+10])
line, = ax.plot([], [], 'b', marker='o')

def animate(i):
    line.set_data(x[:i], y[:i])
    return line,

ani = FuncAnimation(fig, animate, frames=steps, interval=50, blit=True)

plt.title('2D Random Walk Animation')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)
plt.show()